package app.framework.freemarker.util;

import app.framework.constant.FrontConstants;
import app.framework.freemarker.loader.AppTemplateLoader;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.ErrorUtil;

import java.io.File;

/**
 * @author mh.z
 */
public class FreeMarkerConfigUtil {

    /**
     * 创建 FreeMarker 配置
     *
     * @param basePath
     * @param delaySecond
     * @return
     */
    public static Configuration createConfiguration(String basePath, Integer delaySecond) {
        CheckUtil.notNull(basePath, "basePath null");
        CheckUtil.notNull(delaySecond, "delaySecond null");

        Configuration freeMarkerConfig = new Configuration(Configuration.VERSION_2_3_22);
        // 默认编码
        freeMarkerConfig.setDefaultEncoding(FrontConstants.TEMPLATE_DEFAULT_ENCODING);
        // 异常处理方式
        freeMarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        // 缓存时间
        freeMarkerConfig.setTemplateUpdateDelay(delaySecond);

        try {
            if (basePath.startsWith(FrontConstants.TEMPLATE_CLASSPATH_PREFIX)) {
                // 类路径的资源
                //
                ClassLoader classLoader = FreeMarkerConfigUtil.class.getClassLoader();
                String basePackagePath = basePath.substring(FrontConstants.TEMPLATE_CLASSPATH_PREFIX.length());
                ClassTemplateLoader loader = new ClassTemplateLoader(classLoader, basePackagePath);
                freeMarkerConfig.setTemplateLoader(new AppTemplateLoader(loader));
            } else if (basePath.startsWith(FrontConstants.TEMPLATE_FILE_PREFIX)) {
                // 文件系统的资源
                //
                String fileName = basePath.substring(FrontConstants.TEMPLATE_FILE_PREFIX.length());
                File file = new File(fileName);
                FileTemplateLoader loader = new FileTemplateLoader(file);
                freeMarkerConfig.setTemplateLoader(new AppTemplateLoader(loader));
            } else {
                // 默认文件系统的资源
                File file = new File(basePath);
                FileTemplateLoader loader = new FileTemplateLoader(file);
                freeMarkerConfig.setTemplateLoader(new AppTemplateLoader(loader));
            }
        } catch (Exception e) {
            throw ErrorUtil.sneakyError(e);
        }

        return freeMarkerConfig;
    }

}
